package com.zzzzzz.test;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInitializer/* implements WebApplicationInitializer */{

	public void onStartup(ServletContext container) throws ServletException {
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();  
		container.addListener(new ContextLoaderListener(context));
		context.setConfigLocation("com.zzzzzz.config");
		context.refresh();
		
		ServletRegistration.Dynamic dispatcher = container.addServlet("appServlet", new DispatcherServlet(context));
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("/");

		FilterRegistration filterRegistration = container.addFilter("encodingFilter", new CharacterEncodingFilter());
		filterRegistration.setInitParameters(getCharacterEncodingFilterParam());
		filterRegistration.addMappingForUrlPatterns(null, false, "/");
		
		container.addFilter("shiroFilter", new DelegatingFilterProxy()).addMappingForUrlPatterns(null, false, "/*");
	}
	
	private Map<String, String> getCharacterEncodingFilterParam() {
		Map<String, String> characterEncodingFilterParam = new HashMap<String, String>();
		characterEncodingFilterParam.put("encoding", "UTF-8");
		characterEncodingFilterParam.put("forceEncoding", "true");
		return characterEncodingFilterParam;
	}

}
